package com.qqonline.conmon.net;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

import com.qqonline.conmon.ByteUtil;
import com.qqonline.conmon.DATA;
import com.qqonline.interfaces.IUrlGetable;

public class GetByHttpUrlConnection implements IUrlGetable {

	private static final String TAG="GetByHttpUrlConnection";
	private HttpURLConnection conn=null;
	private int connectionTimeOut=DATA.NETWORDCONNECTTIMEOUT,readTimeOut=0;
	@Override
	public byte[] getUrl(String url) {
		Log.i(TAG,"Url: "+url);
		byte[] bytes=null;
		try {
			URL urlGet=new URL(url);
			conn=(HttpURLConnection) urlGet.openConnection();
			conn.setConnectTimeout(connectionTimeOut);
			if (readTimeOut > 0) {
				conn.setReadTimeout(readTimeOut);
			}
			 conn.setDoInput(true);
	         conn.setRequestMethod("GET");
	         conn.setRequestProperty("Content-Type", "text/html");
	         conn.setRequestProperty("Accept-Charset", "utf-8");
	         conn.setRequestProperty("contentType", "utf-8");       
	         if(conn.getResponseCode() == 200){
	        	 InputStream is=conn.getInputStream();
	        	 bytes=ByteUtil.inputStreamToByteArray(is);
	        	 is.close();
	         }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bytes;
	}

	@Override
	public void setConnectTimeout(int timeout) {
		this.connectionTimeOut=timeout;

	}

	@Override
	public void setReadTimeout(int timeout) {
		this.connectionTimeOut=timeout;

	}

	@Override
	public void release() {
		if (conn != null) {
			Log.i(TAG,"release url:"+conn.getURL().toString());
			conn.disconnect();
		}	
	}

}
